var categoryDAL = require('../DAL/categoryDAL');
var productDAL = require('../DAL/productDAL');
var async = require('async');

function categoryController(app) {
	// body...
	/* GET home page. */
	//app.get方法第一个参数是我们添加网站可以请求的地址
	app.get('/category', function(req, res, next) {
		//res.render方法的第一个参数是我们请求地址对应的网页文件名
		res.render('Category/index', {
			title: 'Express'
		});
	});

	//分类页面、
	app.get('/gallery/:id', function(req, res) {
		var category_id = req.params.id;
		var pager = 1;
		console.log(category_id);
		res.redirect('/gallery/' + category_id + '/pager/' + pager);
	});

	//分类页面分页
	app.get('/gallery/:id/pager/:page', function(req, res) {
		//res.render方法的第一个参数是我们请求地址对应的网页文件名
		var category_id = req.params.id;
		var currentpage = parseInt(req.params.page);
		//分页方法
		//定义分页参数
		//var currentpage = 1; //当前页
		var pagercounts = 1; //页面总数
		var previouspage = 1; //上一页
		var nextpage = 1;
		//设置分页 每页显示数据条数
		var pageSize = 20;

		//应用async模块的api:parallel处理并行无关联操作
		async.parallel({ //控制流程1:多级菜单加载
			categorylist: function(done) {
				//处理逻辑
				categoryDAL.getCategoryAll(function(catelist) {
					//循环构造数组对象模型
					var categorylist = create_objectArrayList(catelist, 0);

					done(null, categorylist);
				});
			}, //控制流程2:新品发布前五项
			productlistPager: function(done) {
				productDAL.getGoodsListPagerByCateId(category_id, currentpage, pageSize, function(productlist) {
					done(null, productlist);
				});
			}, //控制流程3:用户信息
			userInfo: function(done) {
				var userInfo = req.session.customer;
				done(null, userInfo);
			},//控制流程4 当前分类商品总数
			goodsCounts:function(done) {
				productDAL.getGoodsCountsByCateId(category_id,function(count) {
					done(null, count);
				});
			}
		}, function(err, results) {

			//将上面几个步骤数据操作并行处理，然后在这里一起操作，提供运行效率
			var counts = parseInt(results.goodsCounts);

			//分页信息处理
			//计算总页数
			if((counts % pageSize) > 0) {
				//有余数，数据不足一整页
				pagercounts = parseInt(counts / pageSize) + 1;
			} else {
				//数据正好填满整页
				pagercounts = parseInt(counts / pageSize);
			}
			//设置上一页
			if(currentpage <= 1) {
				previouspage = 1;
			} else {
				previouspage = currentpage - 1;
			}
			//设置下一页
			if(currentpage >= pagercounts) {
				nextpage = pagercounts;
			} else {
				nextpage = currentpage + 1;
			}

			res.render('gallery', {
				categorylist: results.categorylist,
				productlist: results.productlistPager,
				currentpage: currentpage,
				previouspage: previouspage,
				nextpage: nextpage,
				pageSum: pagercounts,
				cate_id:category_id,
				userInfo: results.userInfo
			});
		});

	});

	//递归构造树型数组对象
	function create_objectArrayList(data, pid) {
		pid = pid || 0;
		var list = [];
		data.map(function(item) {
			if(item.up_id == pid) {
				item.list = create_objectArrayList(data, item.category_Id);
				list.push(item);
			}
		});
		return list;
	}
}

module.exports = categoryController;